package com.example.carrierapp.util;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.example.carrierapp.common.CarrierApplication;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @包名：com.cmcc.library.widgets.crash
 * @类名：CrashHandler
 * @描述：(异常处理的类)
 * @时间：2015-8-21下午2:47:58
 * @版本：1.0.0
 */
public class CrashHandler implements UncaughtExceptionHandler {

    //系统默认的uncaughtException处理类
    private UncaughtExceptionHandler mDefaultHandler;
    //CrashHandler实例
    private static CrashHandler instance = new CrashHandler();
    private Context mContext;
    //存储设备信息和异常信息
    private Map<String, String> infos = new HashMap<String, String>();
    //格式化日期,作为日志文件名的一部分
    private SimpleDateFormat sdFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
    //保存日志文件的目录
    private String path = "/crash/";

    private CrashHandler() {
    }

    //获取CrashHandler实例
    public static CrashHandler getInstance() {
        return instance;
    }

    /**
     * @param context
     * @方法名：init
     * @描述：(设置CrashHandler作为程序的默认异常处理类)
     * @输出：void
     * @作者：Administrator
     */
    public void init(Context context) {
        mContext = context;
        //获取系统默认的uncaughtException处理类
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        //设置CrashHandler作为程序默认处理类
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (!handleException(ex) && mDefaultHandler != null) {
            //用户未处理则让系统默认的处理器处理
            mDefaultHandler.uncaughtException(thread, ex);
        } else {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                Log.e("Crashlog error:", e.toString());
            }
            //退出程序
            ((CarrierApplication) mContext).exitApp();
            android.os.Process.killProcess(android.os.Process.myPid());
            System.exit(1);
        }

    }

    /**
     * @param ex
     * @return 未处理异常返回false, 否则, 返回true
     * @方法名：handleException
     * @描述：(异常的处理)
     * @输出：boolean
     * @作者：Administrator
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }

        new Thread() {
            public void run() {
                Looper.prepare();
                Toast.makeText(mContext, "很抱歉,程序出现异常,即将退出.", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }

            ;
        }.start();

        //收集设备参数信息   
        collectDeviceInfo(mContext);
        //保存日志文件   
        saveCrashInfo2File(ex);
        return true;
    }

    /**
     * @param context
     * @方法名：collectDeviceInfo
     * @描述：(收集设备参数信息)
     * @输出：void
     * @作者：Administrator
     */
    private void collectDeviceInfo(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            if(pm==null)
            {
                LogUtil.e("CrashHandler pm is null");
                return;
            }
            PackageInfo info = pm.getPackageInfo(context.getPackageName(),
                PackageManager.GET_ACTIVITIES);
            String versionName = info.versionName == null ? "null" : info.versionName;
            String versionCode = info.versionCode + "";
            infos.put("versionName", versionName);
            infos.put("versionCode", versionCode);
        } catch (NameNotFoundException e) {
            String tag = "an error occured when collect package info:";
            Log.e("Crashlog ", tag + e.toString());
        }

        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                infos.put(field.getName(), field.get(null).toString());
                Log.d("Crashlog ", field.getName() + " : " + field.get(null));
            } catch (Exception e) {
                Log.e("Crashlog ", "an error occured when collect crash info", e);
            }
        }
    }

    /**
     * @param ex 未捕获的异常信息
     * @return 保存的日志文件名
     * @方法名：saveCrashInfo2File
     * @描述：(保存日志文件)
     * @输出：String
     * @作者：Administrator
     */
    private String saveCrashInfo2File(Throwable ex) {
        StringBuffer buffer = new StringBuffer();
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            buffer.append(key + "=" + value + "\n");
        }

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        buffer.append(result);
        try {
            //			long timetamp = System.currentTimeMillis();
            String time = sdFormat.format(new Date());
            String fileName = time + ".log";
//            String fileName = Build.BRAND + "-" + Build.MODEL + "-" + Build.VERSION.RELEASE + "-"+ time + ".log";
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                String pathString = Environment.getExternalStorageDirectory().getAbsolutePath() + path;
                File dir = new File(pathString);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                FileOutputStream fos = new FileOutputStream(pathString + fileName);
                fos.write(buffer.toString().getBytes());
                fos.flush();
                fos.close();
            }
            return fileName;
        } catch (Exception e) {
            Log.e("log ", "an error occured while writing file...", e);
        }
        return null;
    }

}
